package com.eipc;

import org.androidpn.sdk.Constants;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.media.AudioManager;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.net.wifi.WifiManager;
import com.eipc.event.OnBarClickListener;
import com.eipc.event.TagValue;
import com.eipc.util.Tools;
import com.eipc.util.UpdateManager;

public class MainActivity extends CommonActivity {
	private final static int DIALOG_PERSON_SETTING = 1 ;//个性设置对话框
	private final static int DIALOG_OTHER_SETTING = 2;//其他设置对话框
	
	private AudioManager mAudioManager;
	private WifiManager myWifimanager;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mInflater = getLayoutInflater();
        initView();
        mTitle.setBackgroundColor(0);
        if(mLocale==LANGUAGE_CHINESE)
        	mTitle.loadUrl("file:///android_asset/html/title.html");
        else
        	mTitle.loadUrl("file:///android_asset/html-en/title.html");
        
        
        try{
        	TelephonyManager mTelephonyMgr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); 
        	String imsi = mTelephonyMgr.getDeviceId().toLowerCase();  
        	mHelper.put(Constants.XMPP_USERNAME,imsi);      
        }catch(Exception e){
        	Log.e("-----XMPP_USERNAME-----","error");
        }
        
        try{
        	myWifimanager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
        	if(myWifimanager.isWifiEnabled()){
        		if (myWifimanager.getWifiState()!=WifiManager.WIFI_STATE_ENABLING){
        			myWifimanager.setWifiEnabled(false);
        		}
        	}
        }catch(Exception e){
        	Log.e("-----close wifi-----","error");
        }
                
        //设为震动+最大音量
        try{
        	mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
        	mHelper.put(PERFERENCE_MODE, false);
        	mAudioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, mAudioManager.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION), 0);
        	mAudioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, mAudioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM), 0);
        	mAudioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON);
        }catch(Exception e){
        	Log.e("-----set audio -----","error");
        }
		
    	
    	
    	try {
			setWallpaper(getResources().openRawResource(R.drawable.thumbs));
		} catch(Exception e){
			Log.e("-----setWallpaper--------","error");
		}
		
		try {
			SharedPreferences sdkPreferences = getSharedPreferences(Constants.SDK_PREFERENCES, Context.MODE_PRIVATE);
			String mobileID = sdkPreferences.getString(Constants.XMPP_USERNAME,"");
			String myName = mDB.getMyName(mobileID);
			mBar.setMiddleText("EIPC - "+myName);
		} catch(Exception e){
			Log.e("-----set my name--------","error");
		}
		
    }
	@Override
	protected void updateView(){
		super.updateView();
		setTitle();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(mDB!=null) mDB.close();
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		final ListView lv = (ListView)mInflater.inflate(R.layout.list, null);
		switch(id){
			case DIALOG_PERSON_SETTING:
				builder.setTitle(R.string.person_setting);
				lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,android.R.id.text1,mRe.getStringArray(R.array.person_setting)));
				lv.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						Intent i = null;
						switch(position){
							case 0:  //关于输入法设置
								i = new Intent("android.settings.INPUT_METHOD_SETTINGS");
								startActivity(i);
								dismissDialog(DIALOG_PERSON_SETTING);
								break;
							case 1:   //语言设置
								lv.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,android.R.id.text1,mRe.getStringArray(R.array.language)));
								lv.setOnItemClickListener(new OnItemClickListener() {
									@Override
									public void onItemClick(
											AdapterView<?> parent, View view,
											int position, long id) {
										switch(position){
											case 0:  //中文
												if(mLocale!=LANGUAGE_CHINESE)
													switchLanguage(LANGUAGE_CHINESE);
												break;
											case 1: //英文
												if(mLocale!=LANGUAGE_ENGLISH)
													switchLanguage(LANGUAGE_ENGLISH);												
												break;
										}
										removeDialog(DIALOG_PERSON_SETTING);
									}
								});
								break;
						}
					}
				});
				break;
			case DIALOG_OTHER_SETTING:
				builder.setTitle(R.string.other_setting);
				lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,android.R.id.text1,mRe.getStringArray(R.array.other_setting)));
				lv.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						dismissDialog(DIALOG_OTHER_SETTING);
						Intent i = null;
						switch(position){
							case 0:   //时间设置
								i = new Intent("android.settings.DATE_SETTINGS");
								startActivity(i);
								break;
							case 1:   //声音和显示设置
								i = new Intent("com.android.settings.SOUND_SETTINGS");
								startActivity(i);
								break;
							case 2:  //关于手机设置
							try {
								new AlertDialog.Builder(MainActivity.this).setTitle((String)lv.getItemAtPosition(position))
										.setMessage(getString(R.string.about_phone,getPackageManager().getPackageInfo(getPackageName(), 0).versionName))
										.setNegativeButton(R.string.btn_close, null).show();
							} catch (NameNotFoundException e) {
							}
								break;
							case 3:
								new UpdateManager().Update(MainActivity.this);
								break;
						}
					}
				});
				break;
		}
		builder.setView(lv);
		return builder.create();
	}
	
	private View buildHeaderView(int txtId){
		TextView tv = (TextView) mInflater.inflate(R.layout.head_text, null);
		tv.setText(txtId);
		return tv;
	}
    
    @Override
    protected void onPostResume() {
    	super.onPostResume();
    	setCurrentActivity(CommonActivity.MAIN);
    }
    
    @Override
    protected void initView() {
    	super.initView();
    	mTitle = (WebView)findViewById(R.id.title);
    	mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
    	mBar.setOnBarClickListener(new OnBarClickListener() {		
			@Override
			public void onClickRight() {
				new PollingTask().execute();
			}
			
			@Override
			public void onClickLeft() {
			}
		});
    	WebSettings webSettings = mTitle.getSettings();  
    	webSettings.setJavaScriptEnabled(true);  //启动javascript
    	mTitle.addJavascriptInterface(new Object(){
    		public void goTo(int id) { 
    			if(id<Ops.length){
    				TagValue tv = Ops[id];
    				if(tv!=null){
    					Intent i = null;
    					switch(tv.type){
	    					case TagValue.ACTIVITY_TYPE:
	    						if(tv.extra!=null){
		    						i = new Intent(MainActivity.this,tv.extra);
		    						startActivity(i);
	    						}
	    						break;
	    					case TagValue.BROWSE_TYPE:
	    						if(tv.url!=null){
		    						i = new Intent(MainActivity.this,WebViewActivity.class);
		    						i.putExtra("url", tv.url);
		    						startActivity(i);
	    						}
	    						break;
	    					case TagValue.DIALOG_TYPE:
	    						if(tv.dialogId!=0){
	    							showDialog(tv.dialogId);
	    						}
	    						break;
	    					case TagValue.OTHER_TYPE:
	    						if(tv.other == TagValue.CALL){
	    							i = new Intent(Intent.ACTION_DIAL);
	    							startActivity(i);
	    						}
	    						else if(tv.other == TagValue.SMS){
	    							Tools.sendMsg(MainActivity.this, "", "");
	    						}
	    						break;
	    					case TagValue.INTENT_TYPE:
	    						startActivity(tv.intent);
	    						break;	
    					}
    				}
    			}
    		}
    	}, "ipc");
    }
    
    private WebView mTitle;
    
    private static TagValue[] Ops = new TagValue[]{
    	new TagValue(ImportNoticeActivity.class),
    	new TagValue(WorkReportActivity.class),
    	new TagValue(SendMessageActivity.class),    	
    	new TagValue(MeReportActivity.class),
    	new TagValue(TagValue.CALL),
    	new TagValue(TagValue.INTENT_TYPE,getMmsIntent()),
    	new TagValue(WeatherActivity.class),
    	new TagValue(ConsultActivity.class),
//    	new TagValue(AroundMapActivity.class),
    	new TagValue(TagValue.INTENT_TYPE,getGameMapIntent()),
    	new TagValue(TicketInfoActivity.class),
    	new TagValue("file:///android_asset/html/eat.html"),
    	new TagValue("file:///android_asset/html/sponsor.html"),
    	new TagValue(TagValue.INTENT_TYPE,getEmployeeIntent()),
    	new TagValue(TagValue.INTENT_TYPE,getEmailIntent()),
    	new TagValue(BusInfoActivity.class), 
//    	new TagValue(com.android.contacts.ContactsListActivity),    	
    	new TagValue(SignTableActivity.class),new TagValue(EverydayVsActivity.class),
    	new TagValue(PlayerRecordActivity.class),new TagValue(DIALOG_PERSON_SETTING),
    	new TagValue(DIALOG_OTHER_SETTING),
    	new TagValue(InstructionActivity.class),
    };
    
    private static Intent getMmsIntent(){
    	ComponentName comp = new ComponentName("com.android.mms","com.android.mms.ui.ConversationList");
    	Intent intent = new Intent();
    	intent.setComponent(comp);
    	intent.setAction("android.intent.action.MAIN");
    	return intent;
    }
    
    private static Intent getEmployeeIntent(){
    	ComponentName comp = new ComponentName("com.android.contacts","com.android.contacts.DialtactsContactsEntryActivity");
    	Intent intent = new Intent();
        intent.setComponent(comp);
        intent.setAction("android.intent.action.MAIN");
    	return intent;
    }
    
   private static Intent getEmailIntent(){
	   ComponentName comp = new ComponentName("com.android.email","com.android.email.activity.Welcome");
   	   Intent intent = new Intent();
       intent.setComponent(comp);
       intent.setAction("android.intent.action.MAIN");
       return intent;
   }
   
   private static Intent getGameMapIntent(){
//	   ComponentName comp = new ComponentName("org.example.touch","org.example.touch.Touch");
	   ComponentName comp = new ComponentName("com.eipc","com.eipc.AroundMapActivity");
   	   Intent intent = new Intent();
       intent.setComponent(comp);
       intent.setAction("android.intent.action.MAIN");
       return intent;
   }
}